package com.zx.notification.admin.service.impl;

import com.zx.core.page.PageInfo;
import com.zx.core.wrapper.ObjectWrapper;
import com.zx.core.wrapper.PageWrapper;
import com.zx.core.wrapper.ResponseWrapper;
import com.zx.feign.client.NotificationServiceClient;
import com.zx.notification.admin.service.ISystemNotificationsService;
import com.zx.notification.common.dao.NotificationPushTasksMapper;
import com.zx.notification.common.dao.SystemNotificationsMapper;
import com.zx.notification.common.mapstruct.SystemNotificationsMapStructMapper;
import com.zx.notification.common.model.NotificationPushTasks;
import com.zx.notification.common.model.SystemNotifications;
import com.zx.notification.common.param.SystemNotificationsParam;
import com.zx.notification.common.utils.NotificationNoUtils;
import com.zx.notification.common.vo.SystemNotificationsVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * description: 系统通知管理服务实现类 <br>
 * create: 2025-10-17
 * </p>
 *
 * @author zhou  xun
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SystemNotificationsServiceImpl implements ISystemNotificationsService {

    private final SystemNotificationsMapper systemNotificationsMapper;
    private final NotificationPushTasksMapper notificationPushTasksMapper;
    private final SystemNotificationsMapStructMapper systemNotificationsMapStructMapper;
    private final NotificationServiceClient notificationServiceClient;

    @Override
    public PageWrapper<SystemNotificationsVO> getSystemNotificationsVOListByPage(SystemNotificationsParam systemNotificationsParam) {
        PageWrapper<SystemNotificationsVO> result = new PageWrapper<>();
        try {
            PageInfo pageInfo = new PageInfo(systemNotificationsParam.getPageNum(), systemNotificationsParam.getPageSize());
            systemNotificationsParam.setPageNum(pageInfo.getPageNum());
            systemNotificationsParam.setPageSize(pageInfo.getPageSize());

            // 查询总数
            Long count = systemNotificationsMapper.getSystemNotificationsListCount(systemNotificationsParam.getUserId(),
                    systemNotificationsParam.getTemplateCode(),
                    systemNotificationsParam.getTitle(),
                    systemNotificationsParam.getBizType(),
                    systemNotificationsParam.getCreateTimeStart(),
                    systemNotificationsParam.getCreateTimeEnd());
            if (count > 0) {
                // 分页查询列表
                List<SystemNotifications> systemNotificationsList = systemNotificationsMapper.getSystemNotificationsListByPage(systemNotificationsParam.getUserId(),
                        systemNotificationsParam.getTemplateCode(),
                        systemNotificationsParam.getTitle(),
                        systemNotificationsParam.getBizType(),
                        systemNotificationsParam.getCreateTimeStart(),
                        systemNotificationsParam.getCreateTimeEnd(),
                        systemNotificationsParam.getPageNum(),
                        systemNotificationsParam.getPageSize());
                List<SystemNotificationsVO> list = systemNotificationsList.stream()
                        .map(systemNotificationsMapStructMapper::systemNotificationsToSystemNotificationsVO)
                        .toList();

                // 设置返回结果
                result.setData(list);
            }
            result.setTotal(count);
            result.setCurrentPageNum(systemNotificationsParam.getPageNum());
            result.setTotalPage(pageInfo);
        } catch (Exception e) {
            log.error("获取系统通知列表时发生错误", e);
            result.fail("获取系统通知列表失败，请稍后重试");
        }

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper addSystemNotification(SystemNotificationsParam systemNotificationsParam) {
        ResponseWrapper result = new ResponseWrapper();

        try {
            // 验证参数
            ResponseWrapper validateResult = validateSystemNotificationsParams(systemNotificationsParam, true);
            if (validateResult.verifyFail()) {
                return validateResult;
            }

            // 创建系统通知对象
            SystemNotifications systemNotifications = systemNotificationsMapStructMapper.systemNotificationsParamToSystemNotifications(systemNotificationsParam);
            systemNotifications.setId(NotificationNoUtils.generateNotificationId());

            // 设置创建信息
            systemNotifications.setCreateTime(LocalDateTime.now());

            // 插入系统通知到数据库
            systemNotificationsMapper.insertSelective(systemNotifications);
        } catch (Exception e) {
            log.error("添加系统通知时发生错误", e);
            result.fail("添加系统通知失败: " + e.getMessage());
            throw e; // 重新抛出异常以触发事务回滚
        }

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper editSystemNotification(SystemNotificationsParam systemNotificationsParam) {
        ResponseWrapper result = new ResponseWrapper();
        try {
            // 验证参数
            ResponseWrapper validateResult = validateSystemNotificationsParams(systemNotificationsParam, false);
            if (validateResult.verifyFail()) {
                return validateResult;
            }

            // 验证系统通知是否存在
            SystemNotifications existingSystemNotification = systemNotificationsMapper.selectByPrimaryKey(systemNotificationsParam.getId());
            if (null == existingSystemNotification) {
                result.fail("系统通知不存在");
                return result;
            }

            // 检查是否已存在发送任务
            List<NotificationPushTasks> pushTasks = notificationPushTasksMapper.selectByNotificationId(systemNotificationsParam.getId());
            if (!CollectionUtils.isEmpty(pushTasks)) {
                // 如果存在推送任务，说明用户已经点击发送了，不能修改
                result.fail("通知已发送，不能修改");
                return result;
            }

            // 更新系统通知信息
            SystemNotifications systemNotificationToUpdate = systemNotificationsMapStructMapper.systemNotificationsParamToSystemNotifications(systemNotificationsParam);
            systemNotificationsMapper.updateByPrimaryKeySelective(systemNotificationToUpdate);
        } catch (Exception e) {
            log.error("编辑系统通知时发生错误", e);
            result.fail("编辑系统通知失败: " + e.getMessage());
            throw e; // 重新抛出异常以触发事务回滚
        }

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper deleteSystemNotification(String systemNotificationId) {
        ResponseWrapper result = new ResponseWrapper();

        try {
            // 验证系统通知是否存在
            SystemNotifications existingSystemNotification = systemNotificationsMapper.selectByPrimaryKey(systemNotificationId);
            if (null == existingSystemNotification) {
                result.fail("系统通知不存在");
                return result;
            }

            // 检查是否已存在发送任务
            List<NotificationPushTasks> pushTasks = notificationPushTasksMapper.selectByNotificationId(systemNotificationId);
            if (!CollectionUtils.isEmpty(pushTasks)) {
                // 如果存在推送任务，说明用户已经点击发送了，不能删除
                result.fail("通知已发送，不能删除");
                return result;
            }

            // 删除系统通知
            systemNotificationsMapper.deleteByPrimaryKey(systemNotificationId);
        } catch (Exception e) {
            log.error("删除系统通知时发生系统错误", e);
            result.fail("删除系统通知失败: " + e.getMessage());
            throw e; // 重新抛出异常以触发事务回滚
        }

        return result;
    }

    @Override
    public ObjectWrapper<SystemNotificationsVO> selectSystemNotificationById(String systemNotificationId) {
        ObjectWrapper<SystemNotificationsVO> result = new ObjectWrapper<>();
        try {
            // 验证系统通知是否存在
            SystemNotifications selectByPrimaryKey = systemNotificationsMapper.selectByPrimaryKey(systemNotificationId);
            if (null == selectByPrimaryKey) {
                result.fail("系统通知不存在");
                return result;
            }

            SystemNotificationsVO systemNotificationsVO = systemNotificationsMapStructMapper.systemNotificationsToSystemNotificationsVO(selectByPrimaryKey);
            result.setData(systemNotificationsVO);
        } catch (Exception e) {
            log.error("获取系统通知信息时发生错误", e);
            result.fail("获取系统通知信息失败，请稍后重试");
        }

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper sendSystemNotification(String systemNotificationId) {
        ResponseWrapper result = new ResponseWrapper();
        try {
            // 验证系统通知是否存在
            SystemNotifications existingSystemNotification = systemNotificationsMapper.selectByPrimaryKey(systemNotificationId);
            if (null == existingSystemNotification) {
                result.fail("系统通知不存在");
                return result;
            }

            // 检查是否已存在发送任务
            List<NotificationPushTasks> pushTasks = notificationPushTasksMapper.selectByNotificationId(systemNotificationId);
            if (!CollectionUtils.isEmpty(pushTasks)) {
                result.fail("通知已发送，请勿重复发送");
                return result;
            }

            // 调用producer服务创建推送任务并发送通知 ,生产者的发送接口会写任务表, 消费者会处理推送任务
            ResponseWrapper resendResult = notificationServiceClient.resendNotification(systemNotificationId);
            return resendResult;
        } catch (Exception e) {
            log.error("发送系统通知时发生错误", e);
            result.fail("发送系统通知失败: " + e.getMessage());
            // 重新抛出异常以触发事务回滚
            throw e;
        }
    }

    /**
     * 验证系统通知参数
     *
     * @param systemNotificationsParam 系统通知参数
     * @param isAdd                    是否为新增操作
     * @return 验证结果
     */
    private ResponseWrapper validateSystemNotificationsParams(SystemNotificationsParam systemNotificationsParam, boolean isAdd) {
        ResponseWrapper result = new ResponseWrapper();

        // 新增时校验必填字段
        if (isAdd) {
            if (null == systemNotificationsParam.getUserId() || systemNotificationsParam.getUserId().isEmpty()) {
                result.fail("用户ID不能为空");
                return result;
            }

            if (null == systemNotificationsParam.getTemplateCode() || systemNotificationsParam.getTemplateCode().isEmpty()) {
                result.fail("模板编码不能为空");
                return result;
            }

            if (null == systemNotificationsParam.getTitle() || systemNotificationsParam.getTitle().isEmpty()) {
                result.fail("通知标题不能为空");
                return result;
            }

            if (null == systemNotificationsParam.getContent() || systemNotificationsParam.getContent().isEmpty()) {
                result.fail("通知内容不能为空");
                return result;
            }

            if (null == systemNotificationsParam.getBizType() || systemNotificationsParam.getBizType().isEmpty()) {
                result.fail("业务类型不能为空");
                return result;
            }

            if (null == systemNotificationsParam.getTargetChannels() || systemNotificationsParam.getTargetChannels().isEmpty()) {
                result.fail("目标渠道不能为空");
                return result;
            }
        }

        return result;
    }
}